package io.hellsinger.vortex.service.utils

import android.os.Build
import io.hellsinger.filesystem.directory.Directory
import io.hellsinger.filesystem.directory.DirectoryEntry
import io.hellsinger.filesystem.directory.DirectoryWalker
import io.hellsinger.filesystem.path.Path
import io.hellsinger.vortex.data.asPath
import kotlinx.coroutines.flow.Flow

fun isObbOrData(path: Path): Boolean {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.R) return false

    return path.endsWith("Android/obb".asPath(scheme = path.scheme)) ||
        path.endsWith(
            "Android/data".asPath(
                scheme = path.scheme,
            ),
        )
}

inline fun <P : Path> Directory<P>.restrictedTreeWalker(
    crossinline restrictedChecker: (Path) -> Boolean = ::isObbOrData,
    crossinline onRestricted: (Path) -> Int = { DirectoryWalker.SKIP },
): Flow<DirectoryEntry<P>> =
    walk(
        object : DirectoryWalker {
            override suspend fun onPreEnterDirectory(path: Path): Int {
                if (restrictedChecker(path)) return onRestricted(path)
                return DirectoryWalker.CONTINUE
            }

            override suspend fun onPostEnterDirectory(path: Path) {
            }

            override suspend fun onEntry(path: Path): Int = DirectoryWalker.CONTINUE
        },
    )
